<template>
  <div class="user-view">
    <div class="user-info">
      <img :src="user.avatar" alt="头像" class="avatar" />
      <div class="user-right">
        <div class="user-info1">
          <p class="username">{{ user.username }}</p>
          <span class="sex">
            <ManOutlined v-if="user.sex === '男'" style="color: #398bfb" />
            <WomanOutlined
              v-else-if="user.sex === '女'"
              style="color: #f1a2ad"
            />
          </span>
        </div>
        <div class="follow-fans" v-if="isCurrentUser">
          <span class="follow" @click="goToFollowList"
            >关注 {{ user.followCount || 0 }}</span
          >
          <span class="fans" @click="goToFansList"
            >粉丝 {{ user.fansCount || 0 }}</span
          >
        </div>
      </div>
      <div v-if="!isCurrentUser" class="follow-button">
        <a-button @click="followAuthor(user.userId, user.isFollowing)">
          {{ user.isFollowing ? "已关注" : "关注" }}
        </a-button>
      </div>
    </div>
    <div class="user-info2">
      <p class="signature">
        <FileTextOutlined style="margin-right: 8px" /> {{ user.signature }}
      </p>
      <p class="birthday">
        <CalendarOutlined style="margin-right: 8px" /> {{ user.birth_day }}
      </p>
    </div>
    <a-divider />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, onUnmounted } from "vue";
import { useLoginUserStore } from "@/store/useLoginUserStore";
import { doFollow, getCurrentUser, getUserInfo } from "@/api/user";
import { getMinioUrl } from "@/utils/minio";
import { ApiResponse } from "@/types";
import {
  FileTextOutlined,
  CalendarOutlined,
  ManOutlined,
  WomanOutlined,
} from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";

interface UserInfo {
  userId: number;
  avatar: string;
  username: string;
  signature: string;
  birth_day: string;
  sex: string;
  followCount: number;
  fansCount: number;
  isFollowing: boolean;
}
const userId = ref<number | null>(null);
const loginUserStore = useLoginUserStore();
const user = ref<Partial<UserInfo>>({
  userId: null,
  avatar: "",
  username: "",
  signature: "",
  birth_day: "",
  sex: "",
  followCount: 0,
  fansCount: 0,
  isFollowing: false,
});

const isCurrentUser = computed(() => {
  const loginUserId = loginUserStore.loginUser?.id;
  const currentUserId = userId.value;
  return (
    loginUserId !== null &&
    loginUserId !== undefined &&
    currentUserId !== null &&
    loginUserId === currentUserId
  );
});

const sexToString = (sex: string) => {
  switch (sex) {
    case "1":
      return "男";
    case "2":
      return "女";
    default:
      return "";
  }
};

const route = useRoute();

const fetchUserInfo = async (userId: number) => {
  try {
    if (isNaN(userId)) {
      console.log("无效的用户id");
      return;
    }
    const res = await getUserInfo(userId);
    console.log("获取到的用户信息", res, res.data);
    console.log("关注情况", res.data.data.isFollowing);
    if (res.data.code === 200 && res.data) {
      user.value = {
        userId: res.data.data.id || null,
        username: res.data.data.username || "",
        avatar:
          getMinioUrl(
            res.data.data.avatar ||
              "/avatar/icon/f9256155491e54bf5e99bf29eece0156_512_512.jpg"
          ) || "",
        birth_day: res.data.data.birth_day || "",
        sex: sexToString(res.data.data.sex) || "",
        signature: res.data.data.signature || "暂无个性签名",
        followCount: res.data.data.followCount || 0,
        fansCount: res.data.data.followerCount || 0,
        isFollowing: res.data.data.isFollowing ?? false,
      };
    } else {
      console.log("转换用户信息失败");
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
};

const followAuthor = async (authorId: number, isFollowing: boolean) => {
  console.log("关注作者", authorId, isFollowing);
  try {
    const res = await doFollow(authorId);
    user.value.isFollowing = !isFollowing;
    if (res.data.code === 200) {
      if (res.data.data.state === 1) {
        console.log("关注成功");
        message.success("关注成功");
      } else if (res.data.data.state === 0) {
        console.log("取关成功");
        message.success("取关成功");
      }
    }
    window.dispatchEvent(new Event("user-info-updated"));
  } catch (error) {
    console.error("关注失败", error);
  }
};

const handleUserInfoUpdated = () => {
  if (userId.value !== null) {
    fetchUserInfo(userId.value);
  }
};

onMounted(() => {
  window.addEventListener("user-info-updated", handleUserInfoUpdated);
});

onUnmounted(() => {
  window.removeEventListener("user-info-updated", handleUserInfoUpdated);
});

onMounted(async () => {
  const id = Number(route.params.userId);
  userId.value = id;
  if (!isNaN(id)) {
    await fetchUserInfo(id);
  }
});

watch(
  () => route.params.userId,
  async (newId) => {
    const id = Number(newId);
    if (!isNaN(id)) {
      userId.value = id;
      await fetchUserInfo(id); // 重新获取用户信息
    }
  },
  { immediate: true }
);

const goToFollowList = () => {
  console.log("跳转到关注列表");
  window.location.href = `/user/followList`;
};
const goToFansList = () => {
  console.log("跳转到粉丝列表");
  window.location.href = `/user/fanList`;
};
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: flex-start;
  justify-content: left;
  margin-top: 20px;
  margin-left: 20px;
}

.avatar {
  width: 90px;
  height: 90px;
  border: 3px solid rgb(57, 139, 251);
  border-radius: 50%;
  object-fit: cover;
}

.user-right {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.user-info1 {
  display: flex;
  margin-top: 12px;
  margin-left: 30px;
  text-align: left;
  gap: 10px;
}

.username {
  font-size: 25px;
  font-weight: bold;
  margin-bottom: 8px;
}

.sex {
  margin-top: 7px;
  font-size: 14px;
  color: #666;
}

.follow-fans {
  display: flex;
  font-size: 14px;
  color: #4c4c4c;
  gap: 16px;
  margin-top: 8px;
  margin-left: 28px;
}

.follow-fans :hover {
  cursor: pointer;
  color: #398bfb;
}

.user-info2 {
  margin-top: 20px;
  margin-left: 25px;
}

.signature {
  font-size: 14px;
  color: #666;
}

.birthday {
  font-size: 14px;
  color: #666;
}

.follow-button {
  margin-left: 25px;
  margin-top: 12px;
}
</style>
